<?php
require_once dirname(__FILE__).'/GoogleClientApi/src/Google_Client.php';
require_once dirname(__FILE__).'/GoogleClientApi/src/contrib/Google_Oauth2Service.php';
require_once dirname(__FILE__).'/CurrentClient.php';
require_once dirname(__FILE__).'/../config/config.php';

function CreateGoogleClient()
{
	$clnt = new Google_Client();
	$clnt->setAccessType('online');
	$clnt->setApplicationName('Mokomasis SQL Tinklapis');
	$clnt->setClientId('254101315660.apps.googleusercontent.com');
	$clnt->setClientSecret('1tKKKOXzMyDNbdBJbTt6oZWx');
	$clnt->setRedirectUri('http://itpancakes.net/egle/SQLPamokos/Authentication/GoogleLogin.php');
	$clnt->setDeveloperKey('AIzaSyDusKISz7KMb8__1_S4T9j1RqYKzF4m564'); // API key
	
	return $clnt;
}

// Sukuria prisijungusio vartotojo objektą
function CreateCurrentClient($user)
{
    $thisUser = new CurrentClient();

    $thisUser->id = $user['id'];
    $thisUser->email = $user['email'];
    $thisUser->name = $user['name'];
    $thisUser->link = $user['link'];
    $thisUser->picture = $user['picture'];
    $thisUser->locale = $user['locale'];

    $loginData = FetchCurrentUserData($thisUser->email);
    $thisUser->isActive = $loginData['IsActive'];
    $thisUser->isAdministrator = $loginData['IsAdmin'];
    $thisUser->allRoles = $loginData['allRoles'];

    return $thisUser;
}

// Autentikacija
$client = CreateGoogleClient();
$oauth2 = new Google_Oauth2Service($client);
session_start();
if(isset($_SESSION[USER_ID_KEY])) {
    $client->revokeToken();
    unset($_SESSION[USER_ID_KEY]);
    $LoginPageUri = "{$RootDirectoryUri}/index.php";
    header( 'Location: '.$LoginPageUri ) ;
}
else
{
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $_SESSION['token'] = $client->getAccessToken();
        $redirect = "{$RootDirectoryUri}/Authentication/GoogleLogin.php";
        header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
        return;
    }
    //var_dump("22", $_GET, $_SESSION['token']); die;

    if (isset($_SESSION['token'])) {
        $client->setAccessToken($_SESSION['token']);
    }

    if ($client->getAccessToken()) {
        $user = $oauth2->userinfo->get();
        
        // Atsiminti vartotoją sesijoje.
        $CurrentClient = CreateCurrentClient($user);
        $_SESSION[USER_ID_KEY] = serialize($CurrentClient);
        
        if ($CurrentClient->isActive && $CurrentClient->isAdministrator)
        {
            $RedirectPageUri = "{$RootDirectoryUri}/AdminPage.php";
            header( 'Location: '.$RedirectPageUri ) ;
        }
        else
        {
            $LoginPageUri = "{$RootDirectoryUri}/index.php";
            header( 'Location: '.$LoginPageUri ) ;
        }
        return;
    } else {
        $authUrl = $client->createAuthUrl();
        header( 'Location: '.$authUrl ) ;
    }
}
?>
